package com.open.party.cloud.view.home.jiCengDangJian.org

import android.os.Bundle
import android.os.Handler
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import cn.sinothk.view.treeView.bean.Node
import cn.sinothk.view.treeView.bean.TreeItemBean
import com.open.party.cloud.R
import com.open.party.cloud.model.PartyOrgBean
import com.open.party.cloud.view.home.jiCengDangJian.org.adapter.OrgTreeViewAdapter
import com.open.party.cloud.viewModel.BizViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.view.xrefresh.XRefreshLayout
import com.sinothk.view.xrefresh.listener.RefreshHandler
import kotlinx.android.synthetic.main.main_fragment_org_list_view.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


open class OrgPartyTreeMainActivity : AppEventBusTitleBaseActivity() {

    var viewModel: BizViewModel? = null
    private var mOrgTreeViewAdapter: OrgTreeViewAdapter? = null

    override fun getLayoutResId(): Int = R.layout.org_party_activity_list_view

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("中共六盘水市组织部")

        initDataView()
    }

    private fun initDataView() {

        viewModel = BizViewModel()
        loadingTipView.showLoading("加载中")
        viewModel!!.getPartyOrgList("520200")

        refreshLayout.setRefreshEnable(true)
        refreshLayout.setLoadMoreEnable(false)
        refreshLayout.setRefreshHandler(object : RefreshHandler {
            override fun onLoadMore(refresh: XRefreshLayout?) {
            }

            override fun onRefresh(refresh: XRefreshLayout?) {
                Handler().postDelayed({
                    viewModel!!.getPartyOrgList("520200")
                }, 500)
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<ArrayList<PartyOrgBean>>) {

        if ("getPartyOrgList" != result.eventType) {
            return
        }

        refreshLayout.refreshComplete()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    initView(result.data)
                    loadingTipView.showContent()
                } else {
                    loadingTipView.showError("数据异常")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                loadingTipView.showError("Token过期，请重新登录")
            }
            else -> {
                loadingTipView.showError(result.msg)
            }
        }
    }

    private fun initView(data: ArrayList<PartyOrgBean>) {

        val mTreeData: ArrayList<Node<*, *>>? = createTreeData(data)

        mOrgTreeViewAdapter = OrgTreeViewAdapter(
            treeListView, this, mTreeData,
            1
        )

        mOrgTreeViewAdapter!!.setOnItemListener { _, node ->

            val id = node.id.toString()
            if (XUtils.string().isEmpty(id)) {
                return@setOnItemListener
            }

            XUtils.intent().openActivity(this@OrgPartyTreeMainActivity, PartyMemberListActivity::class.java)
                .putStringExtra("orgId", node.id.toString())
                .putStringExtra("orgName", node.name)
                .start()
        }

        treeListView!!.adapter = mOrgTreeViewAdapter
    }

    open fun createTreeData(data: ArrayList<PartyOrgBean>?): ArrayList<Node<*, *>>? {
//        val treeData: String =
//            "[{\"id\":\"4\",\"pid\":\"1\",\"name\":\"第一党小组\"},{\"id\":\"5\",\"pid\":\"1\",\"name\":\"第二党小组\"},{\"id\":\"1\",\"pid\":\"0\",\"name\":\"总公办\"},{\"id\":\"2\",\"pid\":\"0\",\"name\":\"党总支\"},{\"id\":\"13\",\"pid\":\"2\",\"name\":\"第一党支部\"}]"
//        val treeItemBeanList = JSON.parseArray(treeData, TreeItemBean::class.java)
//        return getNodeList(treeItemBeanList)

        val treeItemBeanList = ArrayList<TreeItemBean>()

        if (data != null && data.size > 0) {

            // ============================================================
            val orgLevel1 = data[0]

            for (index1 in orgLevel1.children.indices) {

                val orgItem1 = orgLevel1.children[index1]

                val item1 = TreeItemBean()
                item1.pid = orgLevel1.id
                item1.id = orgItem1.id
                item1.name = orgItem1.orgName
                treeItemBeanList.add(item1)

                for (index2 in orgItem1.children.indices) {
                    val orgItem2 = orgItem1.children[index2]

                    val item2 = TreeItemBean()
                    item2.pid = orgItem1.id
                    item2.id = orgItem2.id
                    item2.name = orgItem2.orgName
                    treeItemBeanList.add(item2)

                    for (index3 in orgItem2.children.indices) {
                        val item3 = TreeItemBean()

                        val orgItem3 = orgItem2.children[index3]

                        item3.pid = orgItem2.id
                        item3.id = orgItem3.id
                        item3.name = orgItem3.orgName
                        treeItemBeanList.add(item3)

                        for (index4 in orgItem3.children.indices) {
                            val item4 = TreeItemBean()

                            val orgItem4 = orgItem3.children[index4]

                            item4.pid = orgItem3.id
                            item4.id = orgItem4.id
                            item4.name = orgItem4.orgName
                            treeItemBeanList.add(item4)
                        }

                        if (orgItem2.userList != null) {
                            for (index_3 in orgItem2.userList.indices) {

                                val item_3 = TreeItemBean()
                                item_3.pid = orgItem2.id
                                item_3.id = ""
                                item_3.name = XUtils.string().getNotNullValue(orgItem2.userList[index_3].userName)
                                treeItemBeanList.add(item_3)
                            }
                        }
                    }

                    if (orgItem1.userList != null) {
                        for (index_2 in orgItem1.userList.indices) {

                            val item_2 = TreeItemBean()
                            item_2.pid = orgItem1.id
                            item_2.id = ""
                            item_2.name = XUtils.string().getNotNullValue(orgItem1.userList[index_2].userName)
                            treeItemBeanList.add(item_2)
                        }
                    }
                }

                if (orgLevel1.userList != null) {
                    for (index_1 in orgLevel1.userList.indices) {

                        val item_1 = TreeItemBean()
                        item_1.pid = orgLevel1.id
                        item_1.id = ""
                        item_1.name = XUtils.string().getNotNullValue(orgLevel1.userList[index_1].userName)
                        treeItemBeanList.add(item_1)
                    }
                }
            }
        }

        return getNodeList(treeItemBeanList)
    }

    open fun getNodeList(treeItemBeanList: List<TreeItemBean>): ArrayList<Node<*, *>> {

        val nodeList: ArrayList<Node<*, *>> = ArrayList()
        if (treeItemBeanList.isNotEmpty()) {
            for (treeItemBean in treeItemBeanList) {
                val node: Node<String, TreeItemBean> = Node(treeItemBean.id, treeItemBean.pid, treeItemBean.name)
                node.setBean(treeItemBean)
                nodeList.add(node)
            }
        }
        return nodeList
    }


}